﻿using Core.AdminUI.V2.Controllers.Base;
using Core.AdminUI.V2.Models;
using Core.AdminUI.V2.Models.AdminRecords;
using Core.FrameWork.Commons.ApiResult;
using Core.FrameWork.Commons.Loging;
using Core.FrameWork.Commons.Mapping;
using Core.FrameWork.Models;
using Core.FrameWork.Models.Models.System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;

namespace Core.AdminUI.V2.Controllers
{
    /// <summary>
    /// 个人中心
    /// </summary>
    public class PersonalController : BaseController
    {
        /// <summary>
        /// 控制器
        /// </summary>
        /// <param name="adminContext"></param>
        public PersonalController(AdminContext adminContext) : base(adminContext)
        {
        }
        #region 视图
        public IActionResult Index()
        {
            Guid GId = Guid.Parse(CurrentUser.Id);

            var adminUserInfo = _adminContext.SysAspNetUsers.Include(s => s.SysAspNetUserRoles).Select(s => new RespAdminUser()
            {
                Email = s.Email,
                Phone = s.Phone,
                TrueName = s.TrueName,
                Id = s.Id,
                RoleIds = s.SysAspNetUserRoles.Select(s => s.RoleId).ToList(),
                CreateTime = s.CreateTime,
                Address = s.Address,
                Company = s.Company,
                Name = s.Name,
                Enabled = s.Enabled,
                LastModifyTime = s.LastModifyTime
            }).FirstOrDefault(s => s.Id.Equals(GId));

            var UserRoles = _adminContext.SysAspNetRoles.Where(m => adminUserInfo.RoleIds.Contains(m.Id)).ToList();

            //查询当前有什么角色
            string roleNames = string.Join(',', UserRoles.Where(m => adminUserInfo.RoleIds.Contains(m.Id)).Select(m => m.Name).ToArray());
            adminUserInfo.Roles = roleNames;


            return View(adminUserInfo);
        }
        #endregion
        #region 接口
        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionDescription("修改用户信息", LogResponseData = true)]
        public CommonResult Update([FromBody] ReqEditAdminUser req)
        {
            var userInfo = _adminContext.SysAspNetUsers.Find(req.Id);

            if (userInfo == null)
            {
                return ApiRespHelp.getError(-100, "指定用户不存在");
            }

            //是否有相同的手机号
            var phCnt = _adminContext.SysAspNetUsers.Count(m => m.Phone == req.Phone && m.Phone != userInfo.Phone);
            if (phCnt > 0)
            {
                return ApiRespHelp.getError(-100, "手机号重复");
            }
            //是否有相同的邮箱
            var EmCnt = _adminContext.SysAspNetUsers.Count(m => m.Email == req.Email && m.Email != userInfo.Email);
            if (EmCnt > 0)
                return ApiRespHelp.getError(-100, "邮箱重复");

            userInfo.TrueName = req.TrueName;
            userInfo.Phone = req.Phone;
            userInfo.Email = req.Email;
            userInfo.Address = req.Address;
            userInfo.Company = req.Company;
            userInfo.LastModifyTime = DateTime.Now;
            userInfo.LastModifyUserId = Guid.Parse(CurrentUser.Id);
            userInfo.LastModifyUserName = CurrentUser.Name;

            int num = _adminContext.SaveChanges();
            if (num > 0)
                return ApiRespHelp.getSuccess("编辑成功");
            return ApiRespHelp.getError(-100, "编辑失败");
        }
        /// <summary>
        /// 获取用户操作日志
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ActionDescription("获取用户操作日志", LogResponseData = true)]
        public CommonResult<RespAdminRecords> GetUserAccessLog()
        {
            var userId = Guid.Parse(CurrentUser.Id);

            var userInfo = _adminContext.SysAspNetUsers.Find(userId);

            if (userInfo == null)
            {
                return ApiRespHelp.GetApiDataList<RespAdminRecords>(-100, "指定用户不存在");
            }
            if (!userInfo.Enabled)
            {
                return ApiRespHelp.GetApiDataList<RespAdminRecords>(-100, "账号已被禁用，请联系管理员");
            }

            //查询当前用户的登录日志
            var accessLog = _adminContext.SysNLogAdminRecords.AsNoTracking().Where(s => s.UserId.Equals(userInfo.Id) && !s.ActionName.Contains("获取用户操作日志")).OrderByDescending(s => s.CreateTime)
            .Take(8).ToList();

            return ApiRespHelp.GetApiDataList<RespAdminRecords>(accessLog.MapTo<SysNLogAdminRecords, RespAdminRecords>());
        }
        #endregion

    }
}
